import { View, Text, Image, WebView } from "@tarojs/components";
import Taro, { useDidShow, useLoad, usePullDownRefresh } from "@tarojs/taro";
import { iconMsg, iconSetting, iconVersion, iconWroing, mineBg, yxxf } from "../../assets/files.js";
import { setStore, getStore } from "../../utils/localStore";
import { useEffect, useState } from "react";
import { iconMineInfo, iconRightGray } from "../../assets/files";
import { navigateTo } from "../../common/_";
import { Button, NavBar } from "@nutui/nutui-react-taro";
import LoginModal from "../../components/login/index.jsx";
import { selectUserInfo } from "../../api/user.js";
import { baseUrl } from "../../utils/request.js";
import useNavInfo from "../../hooks/useNavInfo.js";
import "./index.scss";
import { loginInfo } from "../../api/system.js";

export default function Mine() {
  const [userInfo, setUserInfo] = useState({});
  const [token, setToken] = useState({});
  const [loginVisible, setLoginVisible] = useState(false);
  useLoad(() => {
    setUserInfo(getStore("userInfo"));
    setToken(getStore("token"));

  });

  useDidShow(() => {
    getUserInfo()
  })

  const [useData, setUserData] = useState({})
  async function getUserInfo() {

    const { data } = await selectUserInfo({})
    setUserData(data)
  }


  const goto = (url) => {
    if (!getStore("token")) {
      setLoginVisible(true);
    } else {
      Taro.navigateTo({
        url,
      });
    }
  };

  function loginout() {
    Taro.clearStorage();
    Taro.reLaunch({
      url: "/pages/home/index",
    });
  }

  function toDetail() {
    navigateTo('/packageA/pages/mine-info/index')
  }

  const [version, setVersion] = useState('')

  useEffect(() => {
    getVersionInfo();
  }, [])

  function getVersionInfo() {
    setVersion(Taro.getAccountInfoSync().miniProgram.version);
  }

  const getHead = () => {
    if (useData?.headId) {
      if (useData?.headId.includes('http')) {
        return useData?.headId
      }
      return baseUrl + useData?.headId
    }
    return yxxf
  }

  const [moduleId] = useState("ci15Jz2DJ6ZNkLVVJCATmZv3YZO3yI0BJ4fDE0Gog-4")
  const toMessage = () => {
    // navigateTo("/packageB/pages/messageSetting/index")

    Taro.requestSubscribeMessage({
      tmplIds: [moduleId],
      success(res) {
        console.log(res);
        // console.log(res[moduleId]);
        if (res[moduleId] === 'reject') {
          ioenset()
          Taro.showModal({
            content: "消息通知已关闭，去打开？",
            complete(res) {
              if (res.confirm) {
                ioenset()
              }
            }
          })
        } else {
          Taro.showToast({
            icon: 'none',
            title: '消息通知已打开'
          })
        }
        // setCheckedAsync(true)
      },
      fail(err) {
        console.log(err);

      },
    })



  }

  const ioenset = () => {
    Taro.openSetting({
      withSubscriptions: true,
      success(res) {
        console.log(res.subscriptionsSetting?.mainSwitch)
      },
      fail(err) {
        console.log(err);
      }
    })
  }

  useLoad(() => {
    getRole()
  })

  usePullDownRefresh(() => {
    setTimeout(() => {
      onRefresh()
    }, 300)
  })

  async function onRefresh() {
    Taro.showLoading({
      title: "刷新中...",
    });
    getRole()
    Taro.stopPullDownRefresh(); // 关闭下拉效果
    Taro.hideLoading()
  }

  const [roleList, setRoleList] = useState([])
  const getRole = async () => {
    const { success, data } = await loginInfo()
    if (success) {
      setRoleList(data?.userInfoDto?.roles)
    }
  }

  const updateManager = (showMsg = false) => {
    if (Taro.canIUse("getUpdateManager")) {
      const updateManager = Taro.getUpdateManager();
      // 监听向微信后台请求检查更新结果事件
      updateManager.onCheckForUpdate(function (res) {
        // console.log('onCheckForUpdate====', res);
        // 是否有新版本
        if (res.hasUpdate) {
          // 监听小程序有版本更新事件
          updateManager.onUpdateReady(function () {
            // 有更新就提示用户更新
            Taro.showModal({
              title: "更新提示",
              content: "新版本已经准备好，是否重启应用？",
              success: function (res) {
                console.log("success====", res);
                // res: {errMsg: "showModal: ok", cancel: false, confirm: true}
                if (res.confirm) {
                  // 新的版本已经下载好，调用 applyUpdate 应用新版本并重启
                  updateManager.applyUpdate();
                }
              },
            });
          });
          // 监听小程序更新失败事件
          updateManager.onUpdateFailed(function () {
            // 新的版本下载失败
            Taro.showModal({
              title: "已经有新版本了哟~",
              content: "请您重新加载小程序或关闭app重新打开",
            });
          });
        }else{
          Taro.showToast({title:'已经是最新版本',icon:'none'})
        }
      });
    } else {
      // 不支持使用getUpdateManager事件的话就提示用户更新微信版本
      Taro.showModal({
        title: "提示",
        content:
          "当前微信版本过低，无法使用该功能，请升级到最新微信版本后重试。",
      });
    }
  };

  return (
    <View className="wrap">
      <NavBar style={{ backgroundColor: "transparent", position: 'fixed', left: 0, top: useNavInfo().statusBarHeight }}>
        <span style={{ fontWeight: '400' }}>我的</span>
      </NavBar>
      <View style={{ paddingTop: useNavInfo().statusBarHeight + 54 }}>
        {userInfo ? (
          <View className="userInfoWrap" onClick={() => toDetail()}>
            <Image className="myBg" src={mineBg} />
            <Image className="headImg" src={getHead()} />
            <View className="uInfo">
              <Text className="uName">{useData?.userName}</Text>
            </View>
            <Image className="rightIcon" src={iconRightGray} />
          </View>
        ) : (
          <View className="userWrap">
            <Button
              type="info"
              onClick={() => {
                setLoginVisible(true);
              }}
            >
              点击登录
            </Button>
          </View>
        )}
      </View>

      <View className="mainItemWrap">
        <View
          className="item"
          onClick={() => goto(`/pages/text-record/index`)}
        >
          <Image className="itemIcon" src={iconMineInfo} />
          <Text className="itemDes">测试记录</Text>
          <Image className="rightIcon" src={iconRightGray} />
        </View>

        <View
          className="item"
          onClick={() => goto(`/pages/text-record-detail-error/index`)}
        >
          <Image className="itemIcon" src={iconWroing} />
          <Text className="itemDes">我的错题</Text>
          <Image className="rightIcon" src={iconRightGray} />
        </View>

        <View
          className="item"
          onClick={() => goto(`/pages/voice/index`)}
        >
          <Image className="itemIcon" src={iconWroing} />
          <Text className="itemDes">voice</Text>
          <Image className="rightIcon" src={iconRightGray} />
        </View>

        {roleList?.includes("COUNT") && (
          <>
            <View
              className="item"
              onClick={() => goto(`/packageA/pages/video-total/index`)}
            >
              <Image className="itemIcon" src={iconSetting} />
              <Text className="itemDes">观看统计</Text>
              <Image className="rightIcon" src={iconRightGray} />
            </View>
            {/* <View
              className="item"
              onClick={() => goto(`/packageA/pages/total-all/index`)}
            >
              <Image className="itemIcon" src={iconSetting} />
              <Text className="itemDes">数据统计</Text>
              <Image className="rightIcon" src={iconRightGray} />
            </View> */}
          </>
        )}

        {/* {roleList?.includes("AUDITOR") && (
          <View
            className="item"
            onClick={ioenset}
          >
            <Image className="itemIcon" src={iconMsg} />
            <Text className="itemDes">设置</Text>
            <Image className="rightIcon" src={iconRightGray} />
          </View>
        )} */}



        <View
          className="item"
          onClick={updateManager}
        >
          <Image className="itemIcon" src={iconVersion} />
          <Text className="itemDes">版本号</Text>
          <Text>{version}</Text>
        </View>

        {/* <View
          className="item"
          onClick={()=>{
            Taro.navigateTo({
              url:"/packageB/pages/gongzhong/index"
            })
          }}
        >
          <Image className="itemIcon" src={iconVersion} />
          <Text className="itemDes">公众号</Text>
          <Text>{version}</Text>
        </View> */}

      </View>

      <LoginModal
        visible={loginVisible}
        close={() => {
          setLoginVisible(false);
          setUserInfo(getStore("userInfo"));
        }}
      />

    </View>
  );
}
